﻿@using Sovigaz
@{
    ViewBag.Title = "Chi tiết giao dịch";
    var url = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/');
    string partnerID = Request.Url.AbsolutePath.Split('/')[Request.Url.AbsolutePath.Split('/').Length - 1];
    if (partnerID.StartsWith("P"))
    {
        partnerID = partnerID.Remove(0, 1);
    }
    else
    {
        partnerID = string.Empty;
    }
    Random rand = new Random();
    var repository = new Sovigaz.Permission.Repositories.OrderRepository();
    bool canEdit = repository.CanEdit(Utilities.ConvertUtility.IntParse(Model));
}
<script>
    app.controller('OrderController', function ($scope, $compile, $http, $filter, service) {

        $scope.setSelected = function (id) {
            service.setSelected($scope, id);
        };

        $scope.check = function (id) {
            $scope.checkedObj[id] = !$scope.checkedObj[id];
        };

        $scope.qtyChange = function(id){
            $scope.orderlines[id].OrderQty=parseInt($scope.orderlines[id].OrderQty);
        }
        $scope.capacityChange = function(id){
            $scope.orderlines[id].Capacity=parseInt($scope.orderlines[id].Capacity);
        }

        $scope.selectedChange = function(id){
            var url = '@url' + '@Url.Action("ProductApi", "Api")';
            $http.get(url, {
                params: {
                    ownerID: $scope.partnerID.value,
                    categoryID: $scope.orderlines[id].CategoryID.value,
                    size:$scope.orderlines[id].Size.value
                }
            })
                .success(function (data) {
                    $scope.orderlines[id].TC = data;
                })
                .error(function (data) {
                    service.showModal($scope, $compile, 'error', data.InnerException.InnerException);
                });
        }

        $scope.setSelectedAll = function () {
            var i;
            var keyName= "OrderLineID";
            if ($scope.selectedAll) {
                $scope.selectedAll = true;
                for (i = 0; i < $scope.orderlines.length; i++) {
                    if ($scope.checkedList.indexOf($scope.orderlines[i][keyName]) === -1) {
                        $scope.checkedList.push($scope.orderlines[i][keyName]);
                    }
                    $scope.checkedObj[$scope.orderlines[i][keyName]] = true;
                }
            } else {
                $scope.selectedAll = false;
                for (i = 0; i < $scope.orderlines.length; i++) {
                    if ($scope.checkedList.indexOf($scope.orderlines[i][keyName]) !== -1) {
                        $scope.checkedList.pop($scope.orderlines[i][keyName]);
                    }
                    $scope.checkedObj[$scope.orderlines[i][keyName]] = false;
                }
            }
        };

        $scope.loadCategory = function () {
            var url = '@url' + '@Url.Action("CategoryApi", "Api")';
            $http.get(url)
                .success(function (data) {
                    $scope.categories.length=0;
                    for (var i = 0; i < data.length; i++) {
                        $scope.categories.push({"name":data[i].CategoryName,"value":data[i].CategoryID});
                    }     
                })
                .error(function (data) {
                    service.showModal($scope, $compile, 'error', data);
                });
        };
        
        $scope.load = function () {
            startloading($('#content'));

            var url = '@url' + '@Url.Action("OrderApi", "Api", new { id = Model })';

            $http.get(url)
                .success(function (data) {
                    $scope.order = data;
                    $scope.isDisabled = false;
                    if(data.Status=='I') $scope.isDisabled = true;
                    $scope.orderlines.length=0;

                    for (var i = 0; i < data.OrderLines.length; i++) {
                        $scope.orderlines.push({"OrderLineID":data.OrderLines[i].OrderLineID,"CategoryID":data.OrderLines[i].CategoryID,"OrderQty":data.OrderLines[i].OrderQty,"Size":data.OrderLines[i].Size,"Capacity":data.OrderLines[i].Capacity,"Description":data.OrderLines[i].Description});
                    }
                    for (var i = 0; i < data.OrderLines.length; i++) {
                        $scope.orderlines[i].Size = { name: '', value: data.OrderLines[i].Size };
                        $scope.orderlines[i].CategoryID = { name: '', value: data.OrderLines[i].CategoryID };
                    }

                    $scope.partners.length=0;
                    for (var i = 0; i < data.Partners.length; i++) {
                        $scope.partners.push({"name":data.Partners[i].PartnerName,"value":data.Partners[i].PartnerID});
                    }

                    var model = @Html.Raw(Json.Encode(partnerID));
                    if(data.PartnerID <= 1)
                    {
                        if(!isNaN(parseInt(model,10)))
                            data.PartnerID = parseInt(model);
                    }
                    
                    $scope.type = { name: '', value: data.Type };
                    $scope.status = { name: '', value: data.Status };
                    $scope.partnerID = { name: '', value: data.PartnerID };
                    stoploading($('#content'));
                })
                .error(function (data) {
                    stoploading($('#content'));
                    service.showModal($scope, $compile, 'error', data);
                });
        };

        $scope.add = function () {
            window.location = '@Url.Action("Detail", "Order", new { id = String.Empty })';
        };

        $scope.addInputItem = function() {
            if($scope.orderlines.length >= 10) service.showModal($scope, $compile, 'error', 'Số dòng đơn hàng không vượt quá 10');
            else
            {
                var TC;
                var url = '@url' + '@Url.Action("ProductApi", "Api")';
                var idx=$scope.idx + 1 ;
                $scope.idx=idx;
                $http.get(url, {
                    params: {
                        ownerID: $scope.partnerID.value,
                        categoryID: 1,
                        size: 'L'
                    }
                })
                    .success(function (data) {
                        $scope.orderlines.push({"OrderLineID":-idx,"CategoryID":1,"OrderQty":1,"Size":'L',"Capacity":10,"TC":data,"Description":''});
                        $scope.orderlines[$scope.orderlines.length-1].Size = { name: '', value: 'L' };
                        $scope.orderlines[$scope.orderlines.length-1].CategoryID = { name: '', value: 1 };
                    })
                    .error(function (data) {
                        service.showModal($scope, $compile, 'error', data.InnerException.InnerException);
                    });
            }
        };

        $scope.removeInputItem = function() {
            for (var i = 0; i < $scope.checkedList.length; i++) {
                for (var j = 0; j < $scope.orderlines.length; j++)
                    if($scope.orderlines[j].OrderLineID == $scope.checkedList[i])
                        $scope.orderlines.splice(j,1);
            }
        };

        $scope.save = function () {
            if($scope.orderlines.length==0) service.showModal($scope, $compile, 'error', 'Chi tiết đơn hàng cần ít nhất 1 sản phẩm');
            else
            {
                $scope.order.Status = $scope.status.value;
                $scope.order.Type = $scope.type.value;
                $scope.order.PartnerID = $scope.partnerID.value;
                $scope.order.OrderDate = $filter('date')(Date.parse($scope.order.OrderDate), 'y/MM/dd');
                $scope.order.DeliveryDate = $filter('date')(Date.parse($scope.order.DeliveryDate), 'y/MM/dd');
                $scope.order.OrderLines=$scope.orderlines;

                for (var i = 0; i < $scope.order.OrderLines.length; i++) {
                    $scope.order.OrderLines[i].Size = $scope.order.OrderLines[i].Size.value;
                    $scope.order.OrderLines[i].CategoryID = $scope.order.OrderLines[i].CategoryID.value;
                }
                var url = '@url' + '@Url.Action("OrderApi", "Api")';
                $http.put(url, $scope.order)
                    .success(function(data) {
                        if (@Model === 0) {
                            @{
                                string ourl = Url.Action("Detail", "Order");
                                if (ourl.Contains("/P"))
                                {
                                    ourl = ourl.Remove(ourl.IndexOf("/P"));
                                }
                             }
                            window.location = '@ourl/' + data.OrderID;
                        }
                        $scope.order = data;
                        $scope.orderlines.length=0;

                        for (var i = 0; i < data.OrderLines.length; i++) {
                            $scope.orderlines.push({"OrderLineID":data.OrderLines[i].OrderLineID,"CategoryID":data.OrderLines[i].CategoryID,"OrderQty":data.OrderLines[i].OrderQty,"Size":data.OrderLines[i].Size,"Capacity":data.OrderLines[i].Capacity,"Description":data.OrderLines[i].Description});
                        }
                        for (var i = 0; i < data.OrderLines.length; i++) {
                            $scope.orderlines[i].Size = { name: '', value: data.OrderLines[i].Size };
                            $scope.orderlines[i].CategoryID = { name: '', value: data.OrderLines[i].CategoryID };
                        }

                        for (var i = 0; i < data.Partners.length; i++) {
                            $scope.partners.push({"name":data.Partners[i].PartnerName,"value":data.Partners[i].PartnerID});
                        }

                        $scope.type = { name: '', value: data.Type };
                        $scope.status = { name: '', value: data.Status };
                        $scope.partnerID = { name: '', value: data.PartnerID };
                        stoploading($('#content'));
                        service.showModal($scope, $compile, 'notify', 'Dữ liệu đã được lưu thành công!!!');
                    })
                    .error(function(data) {
                        stoploading($('#content'));
                        service.showModal($scope, $compile, 'error', data);
                    });
                }
        };

        $scope.confirmDelete = function () {
            service.showModal($scope, $compile, 'confirm', 'Bạn có chắc chắn muốn xóa dữ liệu?', 'delete()');
        };

        $scope.back = function () {
            window.location = '@Url.Action("Index", "Order")';
        };       

        $scope.statuslist = [
            { name: 'Mới', value: 'N' },
            { name: 'Đã lập kế hoạch', value: 'I' },
            { name: 'Hoàn Thành', value: 'C' },
        ];

        $scope.types = [
            { name: 'Giao', value: 'G' },
            { name: 'Nhận', value: 'N' },
        ];

        $scope.sizes = [
            { name: 'Lớn', value: 'L' },
            { name: 'Nhỏ', value: 'N' },
        ];

        $scope.idx = 0;
        $scope.checkedObj = [{}];
        $scope.checkedList = [];
        $scope.partners = [{}]; 
        $scope.categories = [{}];  
        $scope.orderlines = [{}]; 
        $scope.disabled = true;

        $scope.load();
        $scope.loadCategory();
    });

    $(function () {
        $("[data-toggle=tooltip]").tooltip();
    });
</script>

<div ng-controller="OrderController">
    @Html.Partial("_PageHeader")
    @Html.Partial("_ToolbarDetail")
    <div id="content" class="content row">
        <form role="form" name="form" autocomplete="off">
            <div class="panel-body">
                <div class="col-lg-2" style="clear: both">
                    @Html.Partial("Control/_Control_TextBox_Disabled", new Dictionary<string, string>
                    {
                        {"Text", "Mã số giao dịch"},
                        {"Model", "order.OrderCode"},
                        {"Name", "orderCode"}
                    })
                </div>
                <div class="col-lg-2">
                    @Html.Partial("Control/_Control_ComboBox", new Dictionary<string, string>
                    {
                        {"Text", "Khách hàng"},
                        {"Model", "partnerID"},
                        {"Name", "partnerID"},
                        {"Options", "partnerID.name for partnerID in partners track by partnerID.value"},
                        {"Disabled","isDisabled"}
                    })
                </div>
                <div class="col-lg-2">
                    @Html.Partial("Control/_Control_Datepicker", new Dictionary<string, string>
                    {
                        {"Text", "Ngày đặt hàng"},
                        {"Model", "order.OrderDate"},
                        {"Name", "orderDate"},
                        {"Disabled","isDisabled"}
                    })
                </div>
                <div class="col-lg-2">
                    @Html.Partial("Control/_Control_Datepicker", new Dictionary<string, string>
                    {
                        {"Text", "Ngày giao dịch"},
                        {"Model", "order.DeliveryDate"},
                        {"Name", "deliveryDate"},
                        {"Disabled","isDisabled"}
                    })
                </div>
                <div class="col-lg-2" style="clear: both">
                    @Html.Partial("Control/_Control_ComboBox_IsDisabled", new Dictionary<string, string>
                    {
                        {"Text", "Tình trạng"},
                        {"Model", "status"},
                        {"Name", "status"},
                        {"Options", "status.name for status in statuslist track by status.value"},
                        {"Disabled", "disabled"}
                    })
                </div>
                <div class="col-lg-2">
                    @Html.Partial("Control/_Control_ComboBox_IsDisabled", new Dictionary<string, string>
                    {
                        {"Text", "Loại giao dịch"},
                        {"Model", "type"},
                        {"Name", "type"},
                        {"Options", "type.name for type in types track by type.value"},
                        {"Disabled", "disabled"}
                    })
                </div>
                <div class="col-lg-8" style="clear: both">
                    @Html.Partial("Control/_Control_TextArea", new Dictionary<string, string>
                    {
                        {"Text", "Ghi chú"},
                        {"Model", "order.Description"},
                        {"Name", "description"},
                        {"Disabled","isDisabled"}
                    })
                </div>
                <div class="col-lg-8" style="clear: both; border-top: 1px solid lightgray; margin-top: 10px; margin-bottom: 10px">
                </div>
                <div class="col-lg-8" style="clear: both">
                    <b>Chi tiết</b>
                </div>

                <div class="col-lg-8" style="clear: both">
                    <button class="btn btn-primary btn-sm" type="button" ng-click="addInputItem()">
                        <i class="fa fa-edit fa-fw"></i>Thêm
                    </button>
                    <button class="btn btn-primary btn-sm" type="button" ng-click="removeInputItem()">
                        <i class="fa fa-edit fa-fw"></i>Xóa
                    </button>
                    <br></br>
                </div>
                <div class="col-lg-8" style="clear: both">
                    <div class="table-responsive">
                        <table class="table table-striped table-bordered table-hover">
                            <colgroup>
                                <col style="width: 50px" />
                                <col style="width: 100px" />
                                <col style="width: 100px" />
                                <col style="width: 100px" />
                                <col style="width: 100px" />
                                <col style="width: 80px" />
                                <col />
                            </colgroup>
                            <thead>
                                <tr>
                                    <th>
                                        <div>
                                            <input ng-model="selectedAll" ng-click="setSelectedAll()" style="margin-left: 10px;" class="center" type="checkbox" >
                                        </div>
                                    </th>
                                    <th>Loại chai
                                    </th>
                                    <th>Số lượng
                                    </th>
                                    <th>Kích thước
                                    </th>
                                    <th>Sức chứa
                                    </th>
                                    <th>Chai TC
                                    </th>
                                    <th>Ghi chú
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr ng-repeat="item in orderlines">
                                    <td class="center" ng-click="setSelected(item.OrderLineID)">
                                        <div>
                                            <input ng-click="check(item.OrderLineID)" ng-model="checkedObj[item.OrderLineID]" class="center" type="checkbox" />
                                        </div>
                                    </td>
                                    <td class="center">
                                        <select ng-model="item.CategoryID" class="form-control" ng-options="categoryID.name for categoryID in categories track by categoryID.value" ng-change="selectedChange($index)" ng-disabled="isDisabled">
                                        </select>
                                    </td>
                                    <td class="center">
                                        <div class="form-group">
                                            <input ng-model="item.OrderQty" name="orderQty{{$index}}" type="text" class="form-control" ng-change="qtyChange($index)" ng-maxlength="2" ng-pattern="/^[0-9., ]+$/" ng-disabled="isDisabled" />
                                            <div class="error-container"
                                                ng-show="form.orderQty{{$index}}.$dirty && form.orderQty{{$index}}.$invalid">
                                                <small class="error"
                                                    ng-show="form.orderQty{{$index}}.$error.maxlength">
                                                    <p style="color: red"><b>Tối đa 2 ký tự</b></p>
                                                </small>
                                                <small class="error"
                                                    ng-show="form.orderQty{{$index}}.$error.pattern" \>
                                                    <p style="color: red"><b>Ký tự không hợp lệ</b></p>
                                                </small>
                                            </div>
                                        </div>
                                        <td class="center">
                                            <select ng-model="item.Size" class="form-control" ng-options="size.name for size in sizes track by size.value" ng-change="selectedChange($index)" ng-disabled="isDisabled">
                                            </select>
                                        </td>
                                    <td class="center">
                                        <div class="form-group">
                                            <input ng-model="item.Capacity" name="capacity{{$index}}" type="text" class="form-control" ng-change="capacityChange($index)" ng-maxlength="2" ng-pattern="/^[0-9., ]+$/" ng-disabled="isDisabled"/>
                                            <div class="error-container"
                                                ng-show="form.capacity{{$index}}.$dirty && form.capacity{{$index}}.$invalid">
                                                <small class="error"
                                                    ng-show="form.capacity{{$index}}.$error.maxlength">
                                                    <p style="color: red"><b>Tối đa 2 ký tự</b></p>
                                                </small>
                                                <small class="error"
                                                    ng-show="form.capacity{{$index}}.$error.pattern">
                                                    <p style="color: red"><b>Ký tự không hợp lệ</b></p>
                                                </small>
                                            </div>
                                        </div>
                                    <td>{{item.TC}}</td>
                                    <td class="center">
                                        <input ng-model="item.Description" type="text" class="form-control" ng-disabled="isDisabled"/></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
